package de.lmu.ifi.pst.uwejsf.framework;

import java.util.HashMap;
import java.util.List;

public class PersistenceManagerContentSelector implements ContentSelector {

	private String navigationNode;
	private Class<?> contentType;
	private String name;
	private Expression expression;
	private boolean expectsList;

	public PersistenceManagerContentSelector(String navigationNode,
			Class<?> contentType, boolean expectsList) {
		this.navigationNode = navigationNode;
		this.contentType = contentType;
		this.expectsList = expectsList;
	}

	@Override
	public Object getContent(ExpressionContextProvider contextProvider) {
		PersistenceManager pm = contextProvider.getPersistenceManager();
		String modelQName = pm.getModelQNameString(contentType
				.getCanonicalName());
		List<?> result = pm.query(modelQName, expression.getExpression(),
				navigationNode, new HashMap<String, Object>(), contextProvider);
		if (expectsList)
			return result;
		else
			return result.isEmpty() ? null : result.get(0);

	}

	@Override
	public Expression getExpression() {
		return expression;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getSourceContentInLink() {
		return null;
	}

	@Override
	public void setExpression(Expression expression) {
		this.expression = expression;

	}

	@Override
	public void setName(String name) {
		this.name = name;

	}

	@Override
	public void setSourceContentInLink(String sourceContentInLink) {
		// NOP
	}

}
